#include <Arduino.h>
#include <SD.h>
#include <FS.h>
#include <WiFi.h>
#include <WiFiClient.h>
#define LGFX_USE_V1
#include <LovyanGFX.hpp>
#define PL_MPEG_IMPLEMENTATION
#include "gui/pl_mpeg.h"
#include <axp20x.h>
#define SDIO_CLK 6
#define SDIO_CMD 7
#define SDIO_D0 5
#define SDIO_D1 -1
#define SDIO_D2 -1
#define SDIO_D3 15
#define SD_SENSOR 4

#define I2C_SDA 14
#define I2C_SCL 21
#define AXP192_IRQ 13
#define RTC_IRQ 12

#define TOUCH_RST 46
#define LCD_DC 45
#define LCD_WR 48
#define LCD_RD 47
#define LCD_D0 0
#define LCD_D1 38
#define LCD_D2 39
#define LCD_D3 40
#define LCD_D4 41
#define LCD_D5 42
#define LCD_D6 2
#define LCD_D7 1
////////////////////////模块IO配置（可复用）/////////////////////////

#define I2C1_SDA 10
#define I2C1_SCL 11

#define I2S_LRCLK 16
#define I2S_BCLK 17
#define I2S_DATA 8

#define IR_LED 10

#define SD_MISO SDIO_D0
#define SD_MOSI SDIO_CMD
#define SD_SCLK SDIO_CLK
#define SD_CS SDIO_D3
// LGFX屏幕定义（注释看不懂）
class LGFX : public lgfx::LGFX_Device
{
public:
    // lgfx::Panel_ILI9341 _panel_instance;
    lgfx::Panel_ST7789 _panel_instance;
    lgfx::Bus_Parallel8 _bus_instance; // 8ビットパラレルバスのインスタンス (ESP32のみ)

public:
    LGFX(void)
    {
        {                                      // バス制御の設定を行います。
            auto cfg = _bus_instance.config(); // バス設定用の構造体を取得します。

            cfg.port = 0;              // 使用するI2Sポートを選択 (0 or 1) (ESP32のI2S LCDモードを使用します)
            cfg.freq_write = 20000000; // 送信クロック (最大20MHz, 80MHzを整数で割った値に丸められます)
            cfg.pin_wr = LCD_WR;       // WR を接続しているピン番号
            cfg.pin_rd = LCD_RD;       // RD を接続しているピン番号
            cfg.pin_rs = LCD_DC;       // RS(D/C)を接続しているピン番号

            cfg.pin_d0 = LCD_D0;
            cfg.pin_d1 = LCD_D1;
            cfg.pin_d2 = LCD_D2;
            cfg.pin_d3 = LCD_D3;
            cfg.pin_d4 = LCD_D4;
            cfg.pin_d5 = LCD_D5;
            cfg.pin_d6 = LCD_D6;
            cfg.pin_d7 = LCD_D7;

            _bus_instance.config(cfg);              // 設定値をバスに反映します。
            _panel_instance.setBus(&_bus_instance); // バスをパネルにセットします。
        }

        {                                        // 表示パネル制御の設定を行います。
            auto cfg = _panel_instance.config(); // 表示パネル設定用の構造体を取得します。

            cfg.pin_cs = -1;   // CS要拉低
            cfg.pin_rst = -1;  // RST和开发板RST相连
            cfg.pin_busy = -1; // BUSYが接続されているピン番号 (-1 = disable)

            // ※ 以下の設定値はパネル毎に一般的な初期値が設定されていますので、不明な項目はコメントアウトして試してみてください。

            cfg.offset_rotation = 1; // 回転方向の値のオフセット 0~7 (4~7は上下反転)
            cfg.readable = true;     // データ読出しが可能な場合 trueに設定
            cfg.invert = true;       // パネルの明暗が反転してしまう場合 trueに設定
            cfg.rgb_order = false;   // パネルの赤と青が入れ替わってしまう場合 trueに設定
            cfg.dlen_16bit = false;  // データ長を16bit単位で送信するパネルの場合 trueに設定
            cfg.bus_shared = false;  // SDカードとバスを共有している場合 trueに設定(drawJpgFile等でバス制御を行います)

            _panel_instance.config(cfg);
        }

        setPanel(&_panel_instance); // 使用するパネルをセットします。
    }
};

LGFX display;

AXP20X_Class axp;
#define screenWidth 320
#define screenHeight 240
int frameid = 0;
SPIClass SDSPI = SPIClass(FSPI);
uint8_t *rgb_buffer;

static int Table_fv1[256] = { -180, -179, -177, -176, -174, -173, -172, -170, -169, -167, -166, -165, -163, -162, -160, -159, -158, -156, -155, -153, -152, -151, -149, -148, -146, -145, -144, -142, -141, -139, -138, -137,  -135, -134, -132, -131, -130, -128, -127, -125, -124, -123, -121, -120, -118, -117, -115, -114, -113, -111, -110, -108, -107, -106, -104, -103, -101, -100, -99, -97, -96, -94, -93, -92, -90,  -89, -87, -86, -85, -83, -82, -80, -79, -78, -76, -75, -73, -72, -71, -69, -68, -66, -65, -64,-62, -61, -59, -58, -57, -55, -54, -52, -51, -50, -48, -47, -45, -44, -43, -41, -40, -38, -37,  -36, -34, -33, -31, -30, -29, -27, -26, -24, -23, -22, -20, -19, -17, -16, -15, -13, -12, -10, -9, -8, -6, -5, -3, -2, 0, 1, 2, 4, 5, 7, 8, 9, 11, 12, 14, 15, 16, 18, 19, 21, 22, 23, 25, 26, 28, 29, 30, 32, 33, 35, 36, 37, 39, 40, 42, 43, 44, 46, 47, 49, 50, 51, 53, 54, 56, 57, 58, 60, 61, 63, 64, 65, 67, 68, 70, 71, 72, 74, 75, 77, 78, 79, 81, 82, 84, 85, 86, 88, 89, 91, 92, 93, 95, 96, 98, 99, 100, 102, 103, 105, 106, 107, 109, 110, 112, 113, 114, 116, 117, 119, 120, 122, 123, 124, 126, 127, 129, 130, 131, 133, 134, 136, 137, 138, 140, 141, 143, 144, 145, 147, 148,  150, 151, 152, 154, 155, 157, 158, 159, 161, 162, 164, 165, 166, 168, 169, 171, 172, 173, 175, 176, 178 };
static int Table_fv2[256] = { -92, -91, -91, -90, -89, -88, -88, -87, -86, -86, -85, -84, -83, -83, -82, -81, -81, -80, -79, -78, -78, -77, -76, -76, -75, -74, -73, -73, -72, -71, -71, -70, -69, -68, -68, -67, -66, -66, -65, -64, -63, -63, -62, -61, -61, -60, -59, -58, -58, -57, -56, -56, -55, -54, -53, -53, -52, -51, -51, -50, -49, -48, -48, -47, -46, -46, -45, -44, -43, -43, -42, -41, -41, -40, -39, -38, -38, -37, -36, -36, -35, -34, -33, -33, -32, -31, -31, -30, -29, -28, -28, -27, -26, -26, -25, -24, -23, -23, -22, -21, -21, -20, -19, -18, -18, -17, -16, -16, -15, -14, -13, -13, -12, -11, -11, -10, -9, -8, -8, -7, -6, -6, -5, -4, -3, -3, -2, -1, 0, 0, 1, 2, 2, 3, 4, 5, 5, 6, 7, 7, 8, 9, 10, 10, 11, 12, 12, 13, 14, 15, 15, 16, 17, 17, 18, 19, 20, 20, 21, 22, 22, 23, 24, 25, 25, 26, 27, 27, 28, 29, 30, 30, 31, 32, 32, 33, 34, 35, 35, 36, 37, 37, 38, 39, 40, 40, 41, 42, 42, 43, 44, 45, 45, 46, 47, 47, 48, 49, 50, 50, 51, 52, 52, 53, 54, 55, 55, 56, 57, 57, 58, 59, 60, 60, 61, 62, 62, 63, 64, 65, 65, 66, 67, 67, 68, 69, 70, 70, 71, 72, 72, 73, 74, 75, 75, 76, 77, 77, 78, 79, 80, 80, 81, 82, 82, 83, 84, 85, 85, 86, 87, 87, 88, 89, 90, 90 };
static int Table_fu1[256] = { -44, -44, -44, -43, -43, -43, -42, -42, -42, -41, -41, -41, -40, -40, -40, -39, -39, -39, -38, -38, -38, -37, -37, -37, -36, -36, -36, -35, -35, -35, -34, -34, -33, -33, -33, -32, -32, -32, -31, -31, -31, -30, -30, -30, -29, -29, -29, -28, -28, -28, -27, -27, -27, -26, -26, -26, -25, -25, -25, -24, -24, -24, -23, -23, -22, -22, -22, -21, -21, -21, -20, -20, -20, -19, -19, -19, -18, -18, -18, -17, -17, -17, -16, -16, -16, -15, -15, -15, -14, -14, -14, -13, -13, -13, -12, -12, -11, -11, -11, -10, -10, -10, -9, -9, -9, -8, -8, -8, -7, -7, -7, -6, -6, -6, -5, -5, -5, -4, -4, -4, -3, -3, -3, -2, -2, -2, -1, -1, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 11, 11, 11, 12, 12, 12, 13, 13, 13, 14, 14, 14, 15, 15, 15, 16, 16, 16, 17, 17, 17, 18, 18, 18, 19, 19, 19, 20, 20, 20, 21, 21, 22, 22, 22, 23, 23, 23, 24, 24, 24, 25, 25, 25, 26, 26, 26, 27, 27, 27, 28, 28, 28, 29, 29, 29, 30, 30, 30, 31, 31, 31, 32, 32, 33, 33, 33, 34, 34, 34, 35, 35, 35, 36, 36, 36, 37, 37, 37, 38, 38, 38, 39, 39, 39, 40, 40, 40, 41, 41, 41, 42, 42, 42, 43, 43 };
static int Table_fu2[256] = { -227, -226, -224, -222, -220, -219, -217, -215, -213, -212, -210, -208, -206, -204, -203, -201, -199, -197, -196, -194, -192, -190, -188, -187, -185, -183, -181, -180, -178, -176, -174, -173, -171, -169, -167, -165, -164, -162, -160, -158, -157, -155, -153, -151, -149, -148, -146, -144, -142, -141, -139, -137, -135, -134, -132, -130, -128, -126, -125, -123, -121, -119, -118, -116, -114, -112, -110, -109, -107, -105, -103, -102, -100, -98, -96, -94, -93, -91, -89, -87, -86, -84, -82, -80, -79, -77, -75, -73, -71, -70, -68, -66, -64, -63, -61, -59, -57, -55, -54, -52, -50, -48, -47, -45, -43, -41, -40, -38, -36, -34, -32, -31, -29, -27, -25, -24, -22, -20, -18, -16, -15, -13, -11, -9, -8, -6, -4, -2, 0, 1, 3, 5, 7, 8, 10, 12, 14, 15, 17, 19, 21, 23, 24, 26, 28, 30, 31, 33, 35, 37, 39, 40, 42, 44, 46, 47, 49, 51, 53, 54, 56, 58, 60, 62, 63, 65, 67, 69, 70, 72, 74, 76, 78, 79, 81, 83, 85, 86, 88, 90, 92, 93, 95, 97, 99, 101, 102, 104, 106, 108, 109, 111, 113, 115, 117, 118, 120, 122, 124, 125, 127, 129, 131, 133, 134, 136, 138, 140, 141, 143, 145, 147, 148, 150, 152, 154, 156, 157, 159, 161, 163, 164, 166, 168, 170, 172, 173, 175, 177, 179, 180, 182, 184, 186, 187, 189, 191, 193, 195, 196, 198, 200, 202, 203, 205, 207, 209, 211, 212, 214, 216, 218, 219, 221, 223, 225 };
static __always_inline uint8_t clamp(int n) {
	if (n > 255) {
		n = 255;
	}
	else if (n & 0x80000000) {
		n = 0;
	}
	return n;
}

void ConvertYUV420SPToBGR(unsigned char* yData,unsigned char* vData,unsigned char* uData,unsigned char* Dst,int ImageWidth,int ImageHeight)
{
    if (ImageWidth < 1 || ImageHeight < 1 || Dst == NULL)
        return ;
 
    int uIdx,vIdx;
    int rdif,invgdif,bdif;
    for (int i = 0;i < ImageHeight;i++){
        for (int j = 0;j < ImageWidth;j++){
            vIdx = (i/2) * (ImageWidth/2) + (j/2);
            uIdx = vIdx;
 
            rdif = Table_fv1[vData[vIdx]];
            invgdif = Table_fu1[uData[uIdx]] + Table_fv2[vData[vIdx]];
            bdif = Table_fu2[uData[uIdx]];
 
            *(Dst++) = clamp(*yData+ bdif);    //b
            *(Dst++) = clamp(*yData - invgdif); //g
            *(Dst++) = clamp(*yData + rdif);    //r
            ++yData;
        }
    }
}

// This function gets called for each decoded video frame
void my_video_callback(plm_t *plm, plm_frame_t *frame, void *user)
{
    // Do something with frame->y.data, frame->cr.data, frame->cb.data
    //plm_frame_to_bgr(frame, rgb_buffer, frame->width * 3);
    ConvertYUV420SPToBGR(frame->y.data, frame->cr.data, frame->cb.data, rgb_buffer, frame->width, frame->height);
    display.startWrite();
    display.setAddrWindow((screenWidth - frame->width) / 2, (screenHeight - frame->height) / 2, frame->width, frame->height);
    display.writePixels((void *)rgb_buffer, frame->width * frame->height, true);
    // display.writePixels((uint16_t *)rgb_buffer, frame->width * frame->height, false);
    display.endWrite();
}

// This function gets called for each decoded audio frame
void my_audio_callback(plm_t *plm, plm_samples_t *frame, void *user)
{
    // Do something with samples->interleaved
}

WiFiClient client;
void buffer_cb(plm_buffer_t *self, void *user)
{
    uint8_t data[1436];
    size_t size = client.read(data, 1436);
    plm_buffer_write(self, data, size);
}

void displayOn(void)
{
    display.writecommand(0x11);
    vTaskDelay(5);
}

void setBrightness(uint8_t b)
{
    if (b > 100)
        b = 100;
    if (b != 0)
    {
    }
    else
    {
        axp.setPowerOutPut(AXP192_DCDC1, AXP202_OFF);
        return;
    }
    axp.setPowerOutPut(AXP192_DCDC1, AXP202_ON);
    axp.setDCDC1Voltage(2480 + (uint16_t)b * 5);
}
void initHardware()
{
    int ret = axp.begin(Wire, AXP192_SLAVE_ADDRESS);
    if (ret == AXP_FAIL)
    {
        Serial.println("AXP Power begin failed");
        while (1)
            ;
    }

    axp.setVWarningLevel1(3450);
    axp.setVWarningLevel2(3400);
    axp.setPowerDownVoltage(3300);

    //! enable all irq channel
    axp.enableIRQ(AXP202_PEK_SHORTPRESS_IRQ, true);
    axp.clearIRQ();

    axp.setPowerOutPut(AXP192_LDO2, AXP202_OFF);
    axp.setPowerOutPut(AXP192_LDO3, AXP202_OFF);
    axp.setPowerOutPut(AXP192_DCDC2, AXP202_OFF);
    axp.setPowerOutPut(AXP192_DCDC1, AXP202_OFF);

    axp.setShutdownTime(AXP_POWER_OFF_TIME_4S);
    axp.setlongPressTime(AXP_LONGPRESS_TIME_2S);
    axp.setStartupTime(AXP192_STARTUP_TIME_128MS);
    axp.adc1Enable(AXP202_BATT_VOL_ADC1 | AXP202_BATT_CUR_ADC1 | AXP202_ACIN_CUR_ADC1 | AXP202_ACIN_VOL_ADC1 | AXP202_VBUS_CUR_ADC1 | AXP202_VBUS_VOL_ADC1, true);

    axp.setChargingTargetVoltage(AXP202_TARGET_VOL_4_2V);
    axp.setAdcSamplingRate(AXP_ADC_SAMPLING_RATE_100HZ);
    axp.setTSmode(AXP_TS_PIN_MODE_DISABLE);
    pinMode(AXP192_IRQ, INPUT_PULLUP);
    pinMode(SD_SENSOR, INPUT_PULLUP);
    display.init();
    display.fillScreen(TFT_BLUE);
    displayOn();
    setBrightness(60);
}

void setup()
{
    Serial.begin(115200);
    pinMode(SD_CS, OUTPUT);
    digitalWrite(SD_CS, HIGH);
    SDSPI.begin(SD_SCLK, SD_MISO, SD_MOSI, -1);
    SD.begin(SD_CS, SDSPI, 40000000);
    Wire.begin(I2C_SDA, I2C_SCL);
    initHardware();

    Serial.println("开始连接WiFi");
    WiFi.begin("lxy", "zah1971896611lxy");
    while (WiFi.isConnected() == false)
        delay(200);
    client.connect("192.168.1.114", 1234);
    if (client.connected() == false)
    {
        Serial.println("无法连接TCP");
        while (1)
            delay(1000);
    }
    rgb_buffer = (uint8_t *)ps_malloc(320 * 240 * 3);
    auto buffer = plm_buffer_create_with_capacity(256 * 1024);
    plm_t *plm = plm_create_with_buffer(buffer, true);
    plm_buffer_set_load_callback(buffer, buffer_cb, NULL);

    // Install the video & audio decode callbacks
    plm_set_video_decode_callback(plm, my_video_callback, NULL);
    plm_set_audio_decode_callback(plm, my_audio_callback, NULL);

    Serial.println("开始解码");
    // Decode
    uint32_t last_millis = millis();
    do
    {
        plm_decode(plm, millis() - last_millis);
        last_millis = millis();
        delay(1);
    } while (!plm_has_ended(plm));

    // All done
    plm_destroy(plm);
    Serial.println("Finished! ");
}

void loop()
{
}